//
//  WQStatusNetViewModel.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/10.
//  Copyright © 2015年 王先强. All rights reserved.
//

import Foundation
import SDWebImage

class WQStatusNetViewModel {
   
   lazy var statusList = [WQStatusViewModel]()
    
    func loadDownRefreshStatus(finishedCallBack: (isSuccess: Bool) -> ()) {
        let since_id = statusList.first?.status?.id ?? 0
        
        //查询网络数据是否本地缓存
        WQStatusDAL.loadStatus(since_id, max_id: 0) { (array) -> () in
            
            guard let statusArr = array else {
                finishedCallBack(isSuccess: false)
                print("返回数据为空")
                return
            }
            var tempList = [WQStatusViewModel]()
            //遍历数组，字典转模型
            for tempDict in statusArr {
                tempList.append(WQStatusViewModel(status: WQStatus(dict: tempDict)))
            }
            self.statusList = tempList + self.statusList
//            print(tempList.count)
            self.cacheSingleImage(finishedCallBack)
        }
        
        
    }
    

    func loadUpRefreshStatus(finishedCallBack: (isSuccess: Bool) -> ()) {
        let max_id = statusList.last?.status?.id ?? 0
        
        WQStatusDAL.loadStatus(0, max_id: max_id) { (array) -> () in
            guard let statusArr = array else {
                print("没有返回数据")
                finishedCallBack(isSuccess: false)
                return
            }
            var tempList = [WQStatusViewModel]()
            //遍历数组，字典转模型
            for tempDict in statusArr {
                tempList.append(WQStatusViewModel(status: WQStatus(dict: tempDict)))
            }
            self.statusList += tempList
//            print(tempList.count)
            self.cacheSingleImage(finishedCallBack)
        }
    }

    
    private func cacheSingleImage(finishedCallBack: (isSuccess: Bool) -> ()) {
        //创建组
        let group = dispatch_group_create()
        for viewModel in self.statusList {
            if viewModel.thumbnailUrls.count != 1 {
                continue
            }
            let url = viewModel.thumbnailUrls.first
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached], progress: nil, completed: { (image, _, _, _, _) -> Void in
                //print("开始缓存单张图片\(url)")
                //任务入组
                dispatch_group_enter(group)
                dispatch_async(dispatch_get_main_queue()) { () -> Void in
                    finishedCallBack(isSuccess: true)
                }
                // 出组
                dispatch_group_leave(group)
            })
        }
        //等待任务出组后在执行，保证单张图片下载完成，主线程容易卡瑟，注意！！！！
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            finishedCallBack(isSuccess: true)
        })
    }

}